package com.jbp.service;

import com.jbp.exception.RRException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


@Service
public class WxLoginUtil {

    private static final Logger logger = LoggerFactory.getLogger(WxLoginUtil.class);

    @Autowired
    private PropertyService propertyService;

    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    public Map<String, Object> getWechatUserInfo(String code) {
        Map<String, Object> map =  getAccessToken(code);

        String accessToken = (String)map.get("access_token");
        String openId = (String)map.get("openid");

        String strUrl = "https://api.weixin.qq.com/sns/userinfo";
        String method = "GET";

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", accessToken);
        params.put("openid", openId);

        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
            Map<String, Object> userInfo = (Map<String, Object>) JSON.parse(rs);
            if(userInfo.containsKey("errcode")) {
                logger.error(String.format("invoke wechat api error with code: %s", userInfo.get("errcode")));
                throw new RRException("调用微信接口失败");
            }
            return userInfo;
        } catch (IOException e) {
            logger.error("invoke wechat api error", e);
            throw new RRException("调用微信接口失败");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }


    /**
     * 根据code获取token
     * @param code
     * @return token和openid
     */
    public Map<String, Object> getAccessToken(String code){
        String strUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String method = "GET";

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("appid", propertyService.getV("wx_login_appid"));
        params.put("secret", propertyService.getV("wx_login_secret"));
        params.put("code", code);
        params.put("grant_type", "authorization_code");

        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
            Map<String, Object> map = (Map<String, Object>) JSON.parse(rs);
            if(map.containsKey("errcode")) {
                logger.error(String.format("invoke wechat api error with code: %s", map.get("errcode")));
                throw new RRException("调用微信接口失败");
            }
            return map;
        } catch (IOException e) {
            logger.error("invoke wechat api error", e);
            throw new RRException("调用微信接口失败");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    public String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
